package Cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.SimpleFormatter;

/**
 * 判断用户是否是第一次登录，如果用户是第一次登录，则响应：您好，欢迎您首次访问
 * 如果不是，则输出上次访问的时间。
 */
@WebServlet("/CookieDemo3")
public class CookieDemo3 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        Cookie[] cookies = request.getCookies();
        boolean flag = false;
        if(cookies !=null && cookies.length > 0){
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if ("lastTime".equals(name)){
                    //1.不是第一次访问
                    flag = true;//表示有lastTime
                    //1.1 设置时间格式
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String format = sdf.format(date);
                    //url编码，消除空格错误
                    String encode = URLEncoder.encode(format,"utf-8");
                    //2 将时间值传入cookie
                    cookie.setValue(encode);
                    //3 设置存活时间
                    cookie.setMaxAge(60*60*24*30);

                    //4 get
                    String value = cookie.getValue();
                    String decode = URLDecoder.decode(value, "utf-8");
                    response.getWriter().write("<h1>欢迎回来，上次访问时间为："+decode+"</h1>");

                    //5 add
                    response.addCookie(cookie);

                    break;
                }

            }
        }


        if(cookies == null || cookies.length == 0 || flag == false){
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = sdf.format(date);
            String encode = URLEncoder.encode(format,"utf-8");
            Cookie cookie = new Cookie("lastTime",encode);
            cookie.setMaxAge(60*60*24*30);
            response.addCookie(cookie);
            response.getWriter().write("<h1>您好，欢迎首次登录</h1>");
        }


    }
}
